package ik.xcj.hostpital.manage.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ik.xcj.hostpital.manage.ex.ServiceException;
import ik.xcj.hostpital.manage.mapper.*;
import ik.xcj.hostpital.manage.pojo.dto.OrderInfoAddNewDTO;
import ik.xcj.hostpital.manage.pojo.dto.OrderInfoUpdateDTO;
import ik.xcj.hostpital.manage.pojo.entity.OrderInfo;
import ik.xcj.hostpital.manage.pojo.entity.Schedule;
import ik.xcj.hostpital.manage.pojo.vo.*;
import ik.xcj.hostpital.manage.service.IOrderInfoService;
import ik.xcj.hostpital.manage.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderInfoServiceImpl implements IOrderInfoService {

    @Autowired
    private IOrderInfoMapper orderInfoMapper;

    @Autowired
    private IHospitalMapper hospitalMapper;

    @Autowired
    private IDepartmentMapper departmentMapper;

    @Autowired
    private IScheduleMapper scheduleMapper;

    @Autowired
    private IPatientMapper patientMapper;

    @Override
    public void addNew(OrderInfoAddNewDTO orderInfoAddNewDTO) {
        log.info("{}",orderInfoAddNewDTO);
        OrderInfo orderInfo = new OrderInfo();
        HospitalVO hospitalVO = hospitalMapper.getStandardByHospitalName(orderInfoAddNewDTO.getHosname());
//        if(hospitalVO == null){
//            String message = "添加订单业务失败，医院不存在";
//            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
//        }
        DepartmentStandardVO departmentVO = departmentMapper.getStandardByDepname(orderInfoAddNewDTO.getDepname());
        if(departmentVO == null){
            String message = "添加订单业务失败，科室不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        ScheduleStandardVO scheduleStandardVO = scheduleMapper.getStandardByDocname(orderInfoAddNewDTO.getDocname());
        if(scheduleStandardVO == null){
            String message = "添加订单业务失败，医生不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        PatientStandardVO patientVO = patientMapper.getStandardById(orderInfoAddNewDTO.getPatientId());
        if(patientVO == null){
            String message = "添加订单业务失败，就诊人不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //在医师日程安排表中添加相应医师预约日程安排信息,更新医师在医师日程安排表的剩余预约数,排班状态
        if(scheduleStandardVO.getAvailableNumber() != 0){
            Schedule schedule = new Schedule();
            Integer availableNumber = scheduleStandardVO.getAvailableNumber();
            scheduleStandardVO.setAvailableNumber(--availableNumber);
            schedule.setWorkDate(new Date());
            BeanUtils.copyProperties(scheduleStandardVO,schedule);
            scheduleMapper.insert(schedule);
        }else {
            if(scheduleStandardVO.getStatus() == 1){
                Schedule schedule = new Schedule();
                Integer status = scheduleStandardVO.getStatus();
                status = 0;
                scheduleStandardVO.setStatus(status);
                BeanUtils.copyProperties(scheduleStandardVO,schedule);
                scheduleMapper.update(schedule);
            }
            String message = "执行预约业务失败，医师剩余预约数不足";
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        //生成订单交易号

        ScheduleStandardVO scheduleNew =scheduleMapper.getStandardByDocname(orderInfoAddNewDTO.getDocname());
        //1.需要医院编号及名称 --医院表
        orderInfo.setHoscode(hospitalVO.getHoscode());
        //2.需要科室编号及名称 --科室表
        orderInfo.setDepcode(departmentVO.getDepcode());
        //3.需要挂号费，医生职称，排班编号，安排日期及时间 --医生日程安排表
        orderInfo.setTitle(scheduleNew.getTitle());
        orderInfo.setAmount(scheduleNew.getAmount());
        orderInfo.setHosScheduleId(scheduleNew.getId().toString());
        //4.需要就诊人id，名称，手机 --就诊人表
        orderInfo.setPatientName(patientVO.getName());
        orderInfo.setPatientPhone(patientVO.getPhone());
        orderInfo.setOrderStatus(1);
        orderInfo.setIsDeleted(0);
        BeanUtils.copyProperties(orderInfoAddNewDTO,orderInfo);
        int rows = orderInfoMapper.insert(orderInfo);
        if(rows != 1){
            String message = "添加订单失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        int i = orderInfoMapper.deleteById(id);
        if(i == 0){
            String message = "删除订单失败，订单不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
    }


    @Override
    public void updateInfoById(Long id, OrderInfoUpdateDTO orderInfoUpdateDTO) {
        log.debug("开始处理【修改订单数据】的业务，id = {}，新的数据={}",id,orderInfoUpdateDTO);
        OrderStandardInfoVO orderStandardInfoVO = orderInfoMapper.getStandardById(id);
        if (orderStandardInfoVO == null){
            String message = "修改订单数据失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoUpdateDTO,orderInfo);
        orderInfo.setId(id);
        log.debug("即将修改订单数据，参数：{}",orderInfo);
        int rows = orderInfoMapper.update(orderInfo);
        if (rows != 1){
            String message = "修改订单数据失败，服务器忙，请稍后尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }


    @Override
    public OrderStandardInfoVO getStandardById(Long id) {
        log.debug("开始处理【根据id查找订单数据】的业务，参数：{}",id);
        OrderStandardInfoVO orderStandardInfoVO = orderInfoMapper.getStandardById(id);
        if (orderStandardInfoVO == null){
            String message = "查找订单数据失败，尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        log.debug("即将返回查询结果：{}",orderStandardInfoVO);
        return orderStandardInfoVO;

    }

    @Override
    public PageInfo<OrderListItemInfoVO> list(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<OrderListItemInfoVO> list = orderInfoMapper.list();
        return new PageInfo<>(list);
    }




    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        HashMap<String, Object> map = new HashMap<>();
        List<OrderCountVo> orderCountVos = orderInfoMapper.selectOrderCount(orderCountQueryVo);

        // 日期列表
        List<String>  dateList=
                orderCountVos.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //统计列表
        List<Integer> countList=
                orderCountVos.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        map.put("dateList",dateList);
        map.put("countList",countList);
        return  map;
    }

    @Override
    public List<OrderMqVo> OrderMqList() {
        List<OrderMqVo> orderMqVos = orderInfoMapper.OrderMqList();
        return  orderMqVos;
    }


}
